import os
import re  # type: ignore
from zipfile import ZipFile

from filetools.base import FileBase, ConfigLoader

# 加载全局配置数据
CONFIG = ConfigLoader().Config('config.json')

class Check(FileBase):
    """
    本类实现各个模式下出现处理非单文件的检查操作，支持 zip,
    """
    def __init__(self):
        super().__init__()

    def CheckEntrance(self, pathlists:list[str]|None=None)->list[tuple[int,str,str]]:
        """
        方法是check类的入口。直接负责获取文件列表，筛选拆分决策使用检查方法
        :return: 返回生成器字典结构
        """
        if pathlists:
            data = []
            for pathlist in pathlists: # 接收路径列表，逐个路径处理
                _,suffix = os.path.splitext(os.path.basename(pathlist))
                match suffix:
                    case ".lang":
                        pass
                    case ".zip":
                        data.append(self.check_zip(pathlist))
        return data

    def check_lang(self, path):
        """
        方法实现语言文件的内容结构检查，确保翻译工作流程的顺利展开
        """
        return None

    def check_zip(self, path:str)->tuple[int,str,list[str]|str]:
        """
        方法实现了检查依据已存在模板检查zip是否符合可翻译类型,并自动实现返回判断压缩包类型
        方法内部按照嵌套多个函数形成流程化处理，依赖上层方法CheckEntrance依次输入参数，内部实现
        完全按照单数据执行
        """
        def level_1(file_path:str)->tuple[str,list[str]]: # 开启包输出名称和列表
            with ZipFile(file_path, 'r') as file:
                name = os.path.basename(str(file.filename))
                file_list = file.namelist()
                return name, file_list

        def level_2(file:tuple[str,list[str]])->tuple[int,str,list[str]|str]:
            """
            检查包是否符合标准结构是可以进行处理,同时返回符合模板的包内部路径
            :return: 返回数据结构元组:name:str,insidepath:list[str]
            """
            name, filelist = file # 获取检查对象名称信息和内部列表信息
            config = CONFIG['Package']
            checkfile = config['file']
            checkcode = config['code']
            insidepath = []
            found = False
            for filetype, filename in checkfile.items():
                for filepath in filelist:
                    if filename in filepath:
                        tag = int(checkcode[filetype])
                        insidepath.append(filepath)
                        found = True
                if not found:
                    insidepath.append(f'NOT {filetype} In Side Package')
            if len(insidepath)<=1:
                insidepath = ''.join(insidepath)
            # 执行返回
            return tag, name, insidepath

        # 主决策触发主循环流程，这里默认顺序调用函数实现逐文件检查
        data = level_1(path)
        data = level_2(data)
        return data

class OpenPackage(FileBase):
    """
    本类实现基于RePackage类的判断后对符合条件的包执行符合条件文件拉取与写入操作
    """
    def __init__(self):
        super().__init__()

    def factory(self):
        pass

    def file_extract(self, paths = None, temppath:str = 'temp'):
        target_path = self.upPath(temppath)
        if target_path is False:
            project_path = self.upPath('MCSAP')
            target_path = self.join_path(project_path,temppath)
            os.mkdir(target_path)
        # filenamelist = Check().templates()
        # for filename in filenamelist:
        #     for path in paths:
        #         with ZipFile(path) as file:
        #             file.extract(filename[0], target_path)

def _test():
    path = ['E:/Project/MCSAP/test/BSL_v8.4.01.2.zip',
            'E:/Project/MCSAP/test/ComplementaryReimagined_r5.1.1.zip',
            'E:/Project/MCSAP/test/FastPBR_v1.1.zip',
            'E:/Project/MCSAP/test/Lux_v1.0.zip',]
    ar = Check()
    # ar.CheckEntrance(path)
    b = ar.CheckEntrance(path)
    for i in b:
        print(i)

if __name__ == "__main__":
    _test()